package com.uca.authority.conf.controller;

import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;

import com.uca.authority.conf.utils.UrlUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import com.uca.common.annotation.Log;
import com.uca.common.config.UcaConfig;
import com.uca.common.enums.BusinessType;
import com.uca.authority.conf.domain.UcaConf;
import com.uca.authority.conf.service.IUcaConfService;
import com.uca.common.core.controller.BaseController;
import com.uca.common.core.domain.AjaxResult;
import com.uca.common.utils.poi.ExcelUtil;

import cn.hutool.core.codec.Base64Decoder;
import cn.hutool.core.codec.Base64Encoder;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.symmetric.AES;
import cn.hutool.crypto.symmetric.SymmetricAlgorithm;

import com.uca.common.core.page.TableDataInfo;

/**
 * UCA-配置Controller
 * 
 * @author 刘殿生
 * @date 2021-03-30
 */
@Controller
@RequestMapping("/conf/conf")
public class UcaConfController extends BaseController
{
    private String prefix = "conf/conf";

    @Autowired
    private IUcaConfService ucaConfService;
    // AES 加密的key 长度
    private static int DEFAULT_KEY_SIZE=256;

    @RequiresPermissions("conf:conf:view")
    @GetMapping()
    public String conf()
    {
        return prefix + "/conf";
    }

    /**
     * 查询UCA-配置列表
     */
    @RequiresPermissions("conf:conf:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(UcaConf ucaConf)
    {
        startPage();
        List<UcaConf> list = ucaConfService.selectUcaConfList(ucaConf);
        return getDataTable(list);
    }

    /**
     * 查询UCA-配置列表
     */
    @PostMapping("/main")
    @ResponseBody
    public TableDataInfo main(UcaConf ucaConf)
    {
        startPage();
        List<UcaConf> list = ucaConfService.selectUcaConfList(null);
        List<UcaConf> list_aes = new ArrayList<UcaConf>();
    	//构建 aes
    	AES aes = null; // aes加密对象
    	byte[] key_decode = null; // key值
    	UcaConf uca_aes = null; // 加密后的aes对象
     	StringBuffer target_buffer = null; // 目标URL拼接
        for(UcaConf uca:list){
           key_decode = Base64Decoder.decode(uca.getPrivateKey()); // 获取key值
           aes = SecureUtil.aes(key_decode); // 创建aes对象
           target_buffer = new StringBuffer();
           String[] split = uca.getCheckType().split(",");
           for (String s: split) {
               if ("1".equals(s)){
            	   target_buffer.append("user=");
            	   target_buffer.append(uca.gettUser());
            	   target_buffer.append("&");
               }
               if ("2".equals(s)){
            	   target_buffer.append("token=");
            	   target_buffer.append(uca.getPrivateKey());
            	   target_buffer.append("&");
               }
               if ("3".equals(s)){
            	   target_buffer.append("corp=");
            	   target_buffer.append(uca.gettCorporation());
               }
           }
           // 加密
           byte[] encrypt = aes.encrypt(target_buffer.toString());
           //转成实体
           String encrypt_base =  Base64Encoder.encode(encrypt);
           String source = "http://127.0.0.1/uca/auth/login?"+encrypt_base+"&sys="+uca.getSourceFlag();
           uca_aes = new UcaConf();
           uca_aes.setSource(source);
           uca_aes.setTargetName(uca.getTargetName());
           list_aes.add(uca_aes);
        }
        return getDataTable(list_aes);
    }

    /**
     * 导出UCA-配置列表
     */
    @RequiresPermissions("conf:conf:export")
    @Log(title = "UCA-配置", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(UcaConf ucaConf)
    {
        List<UcaConf> list = ucaConfService.selectUcaConfList(ucaConf);
        ExcelUtil<UcaConf> util = new ExcelUtil<UcaConf>(UcaConf.class);
        return util.exportExcel(list, "conf");
    }

    /**
     * 新增UCA-配置
     */
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }

    /**
     * 新增保存UCA-配置
     */
    @RequiresPermissions("conf:conf:add")
    @Log(title = "UCA-配置", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(UcaConf ucaConf) throws NoSuchAlgorithmException {
    	 // 获取服务IP
        String ucaIp = UcaConfig.getIp();
        StringBuffer url_buffer = new StringBuffer();
        url_buffer.append(ucaIp);
        
        
        //随机AES生成密钥 采用对称式加密 性能更高，易于更新存储
    	byte[] key = SecureUtil.generateKey(SymmetricAlgorithm.AES.getValue(),DEFAULT_KEY_SIZE).getEncoded() ;
    	String secretKey = Base64Encoder.encode(key);
    	ucaConf.setPrivateKey(secretKey);
    	url_buffer.append("uca/auth/login?");
        url_buffer = UrlUtils.parseUrlParams(ucaConf, url_buffer);
        url_buffer.deleteCharAt(url_buffer.length()-1);
        ucaConf.setSource(url_buffer.toString());
    	return toAjax(ucaConfService.insertUcaConf(ucaConf));
    }

    /**
     * 修改UCA-配置
     */
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Long id, ModelMap mmap)
    {
        UcaConf ucaConf = ucaConfService.selectUcaConfById(id);
        ucaConf.setSource(ucaConf.getSource().substring(0, ucaConf.getSource().indexOf("?")));
        mmap.put("ucaConf", ucaConf);
        return prefix + "/edit";
    }

    /**
     * 修改保存UCA-配置
     */
    @RequiresPermissions("conf:conf:edit")
    @Log(title = "UCA-配置", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(UcaConf ucaConf)
    {
    	 // 获取服务IP
        String ucaIp = UcaConfig.getIp();
        StringBuffer url_buffer = new StringBuffer();
        url_buffer.append(ucaIp);
        url_buffer.append("uca/auth/login?");
        url_buffer = UrlUtils.parseUrlParams(ucaConf, url_buffer);
        url_buffer.deleteCharAt(url_buffer.length()-1);
        ucaConf.setSource(url_buffer.toString());
        return toAjax(ucaConfService.updateUcaConf(ucaConf));
    }

    /**
     * 删除UCA-配置
     */
    @RequiresPermissions("conf:conf:remove")
    @Log(title = "UCA-配置", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(ucaConfService.deleteUcaConfByIds(ids));
    }

}
